package com.wangwenjun.concurrency.chapter14.countdownlatch;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/*
  t1.join t2.join t3.join must hold thread's reference, especially in using thread pool
 */
public class UseCountDownLatch4 {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(4);

        CountDownLatch cdl = new CountDownLatch(3);

        executorService.execute(()->{
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            cdl.countDown();
            System.out.println(cdl.getCount());
        });

        executorService.submit(()->{
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            cdl.countDown();
            System.out.println(cdl.getCount());
        });


        executorService.submit(()->{
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            cdl.countDown();
            System.out.println(cdl.getCount());
        });

        executorService.submit(()->{
            try {
                cdl.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("i am end");
        });
    }
}
